<template>
    <ul class="list">
        <li class="item"
            v-for="item of letters"
            :key="item"
            :ref="item"
            v-on:click="HandleLetterClick"
            @touchstart="handletouchstart"
            @touchmove="handletouchmove"
            @touchend="handletouchend"
        >{{item}}</li>
    </ul>
</template>

<script>
export default {
  name: 'Alphabet',
  props: {
    cities: {
      type: Object
    }
  },
  data () {
    return {
      touchStatus: false,
      timer: null
    }
  },
  methods: {
    HandleLetterClick: function (e) {
      this.$emit('change', e.target.innerText)
    },
    handletouchstart () {
      this.touchStatus = true
    },
    handletouchmove (e) {
      if (this.touchStatus) {
        if (this.timer) {
          clearTimeout(this.timer)
        }
        this.timer = setTimeout(() => {
          const startY = this.$refs['A'][0].offsetTop
          const touchY = e.touches[0].clientY - 80
          const index = Math.floor(((touchY - startY) / 20))
          if (index >= 0 && index < this.letters.length) {
            this.$emit('change', this.letters[index])
            // 如何获取子元素有待改进
            for (var i = 0; i < (this.letters.length); i++) {
              this.$refs[this.letters[i]][0].style.background = '#ffffff'
            }
            this.$refs[this.letters[index]][0].style.background = 'rgba(1, 1, 1, 0.1)'
          }
        }, 15)
      }
    },
    handletouchend () {
      for (var i = 0; i < (this.letters.length); i++) {
        this.$refs[this.letters[i]][0].style.background = '#ffffff'
      }
      this.touchStatus = false
    }
  },
  computed: {
    letters: function () {
      const letters = []
      for (let i in this.cities) {
        letters.push(i)
      }
      return letters
    }
  }
}
</script>

<style scoped lang="stylus">
    .list
        display: flex
        flex-direction: column
        justify-content: center
        position: absolute
        right: 0
        top: 1.58rem
        bottom: 0
        width: 0.4rem
        text-align: center
        .item
          line-height: 0.4rem
          border-radius: 50%
          color: #00B7FF
          font-weight: bold
          background-color: rgba(255, 255, 255, 0.2)
</style>
